//
//  GroupDetailTableViewController.m
//  SuiRan_Demo
//
//  Created by lanou3g on 15-5-4.
//  Copyright (c) 2015年 fzg. All rights reserved.
//

#import "GroupDetailTableViewController.h"

#import "GroupDetailList.h"
#import "GroupDetailCell.h"
#import "GroupDetailCell2.h"
#import "GroupDetail.h"

#define klong (10)

@interface GroupDetailTableViewController () <UIWebViewDelegate>

@property (nonatomic, retain) NSMutableData *allData;
@property (nonatomic, retain) NSMutableArray *allDataArray;
@property (nonatomic, retain) NSMutableString *strData;

@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UILabel *timeLabel;
@property (nonatomic, retain) UILabel *ownerLabel;

@property (nonatomic, retain) UIView *headerView;
@property (nonatomic, retain) UIWebView *webView;

@property (nonatomic, assign) CGFloat cellHeight;

@property (nonatomic, assign) CGFloat start;
@end

@implementation GroupDetailTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self loadData];

    [self refresh];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStyleDone target:self action:@selector(share)];

    
    [self.tableView registerNib:[UINib nibWithNibName:@"GroupDetailCell" bundle:nil] forCellReuseIdentifier:@"GroupDetail"];

    [self.tableView registerNib:[UINib nibWithNibName:@"GroupDetailCell2" bundle:nil] forCellReuseIdentifier:@"GroupDetail2"];
}


- (void)share
{
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"我这在使用随然，￥%%……&*（*（（）*&（"
                                     shareImage:[UIImage imageNamed:@"UMS_douban_icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToWechatTimeline,  UMShareToSms, nil]
                                       delegate:nil];
}


- (void)refresh
{
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    self.tableView.footer.automaticallyRefresh = NO;
}




- (void)loadData
{
    self.allDataArray = [NSMutableArray array];
    
    self.strData = [NSMutableString string];
    
    NSURL *url = [NSURL URLWithString:kGroupDetail];
    NSString *detailUrl = [NSString stringWithString:kDetail(_groupHot.contentid)];
    NSData *paramData = [detailUrl dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //    NSLog(@"~~~~~~~~~~~~~%ld", request.retainCount);
    [request setHTTPMethod:@"POST"];
    
    
    [request setHTTPBody:paramData];
    
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}

- (void)loadMoreData
{
    self.start += 10;
    NSLog(@"%f", _start); 
    
    /*
//    __block typeof (self) weakSelf = self;
//    // 使用AFNetworking
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//    
////    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"1", @"client", @"asc", @"sort", @"BEDF13D6-A735-4416-9F92-D76D6EC4D6B2", @"deviceid", _start, @"start", @"10", @"limit", @"3.0.1", @"version", _groupHot.contentid, @"contentid", @"", @"auth", nil];
//    NSString *parameters = GroupAddComment(_start, _groupHot.contentid);
//    
//    [manager POST:kGroupComment parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        for (NSDictionary *item in responseObject[@"data"][@"list"]) {
//            GroupDetailList * group = [GroupDetailList new];
//            [group setValuesForKeysWithDictionary:item];
//            
//            NSLog(@"~~~~~~~~~");
//            [weakSelf.allDataArray addObject:group];
//            [group release];
//
//        }
//        
//        [weakSelf.tableView reloadData];
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@", error);
//    }];
    
  */
    
    
    NSURL *url = [NSURL URLWithString:kGroupComment];
    
    NSData *paramData = [GroupAddComment(_start, _groupHot.contentid) dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //    NSLog(@"~~~~~~~~~~~~~%ld", request.retainCount);
    [request setHTTPMethod:@"POST"];
    
    
    [request setHTTPBody:paramData];
    
    
    
    [NSURLConnection connectionWithRequest:request delegate:self];
   
    [self.tableView reloadData];
    
    [self.tableView.footer endRefreshing];
    
}

- (void)loadNewData
{
    self.allDataArray = [NSMutableArray array];
    
    NSURL *url = [NSURL URLWithString:kGroupComment];
    
    NSData *paramData = [GroupAddComment(_start, _groupHot.contentid) dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //    NSLog(@"~~~~~~~~~~~~~%ld", request.retainCount);
    [request setHTTPMethod:@"POST"];
    
    
    [request setHTTPBody:paramData];
    
    
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    [self.tableView reloadData];
    
    [self.tableView.header endRefreshing];

}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    NSLog(@"fhsdfhkjdsfjknsjkfhdskj");
    // 修改图片大小
    [webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages() { "
     "var myimg,oldwidth;"
     "var maxwidth = 280;" //缩放系数
     "for(i=0;i < document.images.length;i++){"
     "myimg = document.images[i];"
     "if(myimg.width > maxwidth){"
     "oldwidth = myimg.width;"
     "myimg.width = maxwidth;"
     "myimg.height = myimg.height * (maxwidth/oldwidth) + 90;"
     "}"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    
    
    
    // 禁用用户选择
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    
    
    // 取消链接
    [webView stringByEvaluatingJavaScriptFromString:@"$(document).ready(function () {$(\"a\").removeAttr(\"href\");})"];
    
    
    /*
     // 计算html的高度 可以根据获取到的高度动态设置父视图的高度
     //        NSString *fitHeight = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
     //
     //        NSLog(@"=====%@", fitHeight);
     //
     //
     //        NSString *tempString = [NSString stringWithFormat:@"document.getElementsByTagName('a')[0].innerHTML ='';"];
     //        [webView stringByEvaluatingJavaScriptFromString:tempString];
     */
    
    // 计算html的高度 可以根据获取到的高度动态设置父视图的高度
    CGRect frame = webView.frame;
    frame.size.height = 1;
    webView.frame = frame;
    CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    webView.frame = frame;
    

//    NSLog(@"1`~~~~~%ld", _allDataArray.count);
//    _webViewHeight = webView.frame.size.height;
    [self.tableView reloadData];
}



// 取消当前页面所有点击事件
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //判断是否是单击
    if (navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        return NO;
    }
    return YES;
}



#pragma mark - NSURLConnectionDataDelegate
#pragma mark 开始接受请求结果
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.allData = [NSMutableData data];
}

#pragma mark 接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_allData appendData:data];
}

#pragma mark 数据接收完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_allData options:NSJSONReadingAllowFragments error:nil];
    
//    if (_start != 0) {
        NSLog(@"~~~~~~~~~~~~~~~~~~~~");
        for (NSDictionary *item in dict[@"data"][@"list"]) {
            GroupDetailList * group = [GroupDetailList new];
            [group setValuesForKeysWithDictionary:item];
            
            [self.allDataArray addObject:group];
            [group release];

        }
//    } else {
    
    GroupDetail *groupDet = [GroupDetail new];
    [groupDet setValuesForKeysWithDictionary:dict[@"data"][@"postsinfo"]];
    self.strData = (NSMutableString *)groupDet.html;
    
    
    for (NSDictionary *item in dict[@"data"][@"commentlist"]) {
        GroupDetailList * group = [GroupDetailList new];
        [group setValuesForKeysWithDictionary:item];
        
        [self.allDataArray addObject:group];
        [group release];
    }
    
    
    // webView
    
    self.titleLabel = [[[UILabel alloc] initWithFrame:CGRectMake(klong, 0, CGRectGetWidth([UIScreen mainScreen].bounds) - klong * 2, 50)] autorelease];
    
    self.ownerLabel = [[[UILabel alloc] initWithFrame:CGRectMake(klong, CGRectGetMaxY(_titleLabel.frame), CGRectGetWidth([UIScreen mainScreen].bounds) / 4 + klong * 2, 20)] autorelease];
    
    self.timeLabel = [[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMidX([UIScreen mainScreen].bounds) + CGRectGetWidth(_ownerLabel.frame) - klong * 5, CGRectGetMinY(_ownerLabel.frame), CGRectGetWidth(_ownerLabel.frame), CGRectGetHeight(_ownerLabel.frame))] autorelease];

    
    self.webView = [[[UIWebView alloc] initWithFrame:CGRectMake(klong, CGRectGetMaxY(_ownerLabel.frame), [UIScreen mainScreen].bounds.size.width - klong, 1)] autorelease];
    
    _webView.delegate = self;
    
    [_webView loadHTMLString:self.strData baseURL:nil];
    
//    [_headerView addSubview:_webView];
   
    [self.tableView reloadData];
//    }
}

#pragma mark 发生错误，执行此方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@", error);
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 自定义Header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    self.headerView = [[UIView new] autorelease];
    _headerView.backgroundColor = [UIColor whiteColor];
    
    _titleLabel.text = _groupHot.title;
    _titleLabel.font = [UIFont italicSystemFontOfSize:20];   //加粗及字体大小
    _titleLabel.numberOfLines = 0;
//    _titleLabel.tintColor = [UIColor cyanColor];
    [_headerView addSubview:_titleLabel];
    

    _ownerLabel.font = [UIFont italicSystemFontOfSize:16];
    _ownerLabel.text = _groupHot.userinfo[@"uname"];
    [_headerView addSubview:_ownerLabel];
    
    
    _timeLabel.text = _groupHot.addtime_f;
    _timeLabel.font = [UIFont italicSystemFontOfSize:16];
    _timeLabel.textAlignment = NSTextAlignmentRight;
    [_headerView addSubview:_timeLabel];
    

    
    _webView.scrollView.bounces = NO;
    [_headerView addSubview:_webView];

    //设置header和cell一起滑动
    tableView.tableHeaderView = _headerView;
//
//    //设置header自适应高度
//    [_webView sizeToFit];
//    CGRect newFrame = _headerView.frame;
//    newFrame.size.height = newFrame.size.height + _webView.frame.size.height;
//    _headerView.frame = newFrame;
//    [self.tableView setTableHeaderView:_headerView];
    
    return _headerView;
}

#pragma mark 如果自定义了Header，需要通过下面的方法来设置header的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

//    NSLog(@"height = %f", _webViewHeight);
    return _titleLabel.frame.size.height + _ownerLabel.frame.size.height + _webView.frame.size.height;
}





#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allDataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GroupDetailList *groupDetail = _allDataArray[indexPath.row];
    NSDictionary *dict =  (NSDictionary *)groupDetail.userinfo;
    
    if ([groupDetail.coverimg isEqualToString:@""]) {
        
        GroupDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupDetail" forIndexPath:indexPath];
        
        cell.contectLabel.text = groupDetail.content;
        cell.numberLabel.text = [NSString stringWithFormat:@"%@楼",  groupDetail.cmtnum];
        cell.timeLabel.text = groupDetail.addtime_f;
        cell.likeNumLabel.text = [NSString stringWithFormat:@"%@", groupDetail.likenum];
        
        NSString *nameStr = [NSString stringWithFormat:@"%@", dict[@"uname"]];
        NSString *imageStr = [NSString stringWithFormat:@"%@", dict[@"icon"]];
        
        cell.userNameLabel.text = nameStr;
        
        // 使用SDwebImage下载网络图片
        [cell.userImage sd_setImageWithURL:[NSURL URLWithString:imageStr]];
        
        // content自适应
        CGSize size = CGSizeMake(cell.contectLabel.frame.size.width, 2000);
        NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:13.0f]};
        CGRect rect = [groupDetail.content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        _cellHeight = rect.size.height;
        
//        NSLog(@"contentHeight = %f", cell.contectLabel.frame.size.height);
//        NSLog(@"cellcontentHeight = %f", _cellHeight);
  
        return cell;

    } else {
        
        GroupDetailCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupDetail2" forIndexPath:indexPath];
        
        cell.contectLabel.text = groupDetail.content;
        cell.numberLabel.text = [NSString stringWithFormat:@"%@楼",  groupDetail.cmtnum];
        cell.timeLabel.text = groupDetail.addtime_f;
        cell.likeNumLabel.text = [NSString stringWithFormat:@"%@", groupDetail.likenum];
        
        NSString *nameStr = [NSString stringWithFormat:@"%@", dict[@"uname"]];
        NSString *imageStr = [NSString stringWithFormat:@"%@", dict[@"icon"]];
        
        cell.userNameLabel.text = nameStr;
        
        // 使用SDwebImage下载网络图片
        [cell.userImage sd_setImageWithURL:[NSURL URLWithString:imageStr]];
        [cell.commentImage sd_setImageWithURL:[NSURL URLWithString:groupDetail.coverimg]placeholderImage:[UIImage imageNamed:@"wait"]];
        
        // content自适应
        CGSize size = CGSizeMake(cell.contectLabel.frame.size.width, 2000);
        NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:13.0f]};
        CGRect rect = [groupDetail.content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        _cellHeight = rect.size.height;

        return cell;
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GroupDetailList *groupDetail = _allDataArray[indexPath.row];
   
//    NSLog(@"cellHeight = %f", cell.contectLabel.frame.size.height);
    
    if ([groupDetail.coverimg isEqualToString:@""]) {
        return 75 + _cellHeight;
    } else {
        return 85 + self.tableView.frame.size.width * 99 / 152 + _cellHeight;
    }
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
